package com.durunmin;

import java.io.*;
import java.net.*;

public class Client {


    public static void main(String[] args) throws IOException {

        Socket socket = new Socket();
        //设置超时时间
        socket.setSoTimeout(3000);
        //连接本地
        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(),2000),3000);

        System.out.println("已发起服务器连接，并进入后续流程~");
        System.out.println("客户端信息："+socket.getLocalAddress() + " P: "+socket.getLocalPort());
        System.out.println("服务器信息："+socket.getInetAddress() + " P: "+socket.getPort());

        try{
            todo(socket);
        } catch (Exception e){

            System.out.println("异常关闭");

        }

        //释放资源
        socket.close();
        System.out.println("客户端已退出~");
    }

    public static void todo(Socket socket) throws IOException {

        //构建键盘输入流
        InputStream inputStream = System.in;
        BufferedReader input = new BufferedReader(new InputStreamReader(inputStream));

        //构建socket输出流
        OutputStream outputStream = socket.getOutputStream();
        PrintStream printStream = new PrintStream(outputStream);

        //得到socket输入流
        InputStream socketInputStream = socket.getInputStream();
        BufferedReader bufferedInput = new BufferedReader(new InputStreamReader(socketInputStream));

        boolean flag = true;
        while (flag){

            String str = input.readLine();
            printStream.println(str);

            String resopnse = bufferedInput.readLine();
            System.out.println(resopnse);
            if ("bye".equals(resopnse)){
                flag = false;
            }
        }

        //释放资源
        bufferedInput.close();
        printStream.close();
    }
}
